import mqForMqtt from "./mqForMqtt";
import store from '@/store'
import Vue from 'vue'
import {MQ_TOPIC,MQ_COMMON_TOPIC} from '@/config/linkparam'
import { ACCESS_TOKEN } from "@/store/mutation-types"
/**
 * 主页连接
 */
function connect() {
  return new Promise((resolve, reject) => {
    mqForMqtt.connect(receive, closeCallBack)
      .then((res) => {
        //存入共享池
        store.commit('SET_MQCLIENT', res);
		console.log('放入后:',store.getters)
        //订阅主题
        mqForMqtt.subscribe(res, MQ_TOPIC)
        mqForMqtt.subscribe(res, MQ_COMMON_TOPIC);
        resolve();
      })
      .catch((err) => {
        reject();
        console.log(' :>> ', err);
      })
  })
}

/**
 * 直接发消息 格式为 JSON
 * @param {*} message
 */
async function send(message) {
  console.log('mqClient:',store.getters)
  var mqclient = await store.getters.mqClient;
  if (mqclient) {
    mqForMqtt.publish(mqclient, MQ_TOPIC, JSON.stringify(message))

  } else {
    console.log('mqClient为空 :>> ', mqclient);
  }
}

/**
 * 直接发消息 格式为 JSON  自定义主题
 * @param {*} message
 * @param {*} topic
 */
async function sendByTopic(message,topic) {
  var mqclient = await store.getters.mqClient;
  if (mqclient) {
    console.log('sendtopic :>> ',topic );
    mqForMqtt.publish(mqclient,topic,JSON.stringify(message))

  } else {
    console.log('mqClient为空 :>> ', mqclient);
  }
}

/**
 *  接收的消息通过总线发
 * @param {*} topic
 * @param {*} message
 * @param {*} packet
 */
async function receive(topic, message, packet) {
  //解析message
  var userwpinfo = store.getters;
  // console.log('userwpinfo :>> ', userwpinfo);
  var data = JSON.parse(mqForMqtt.unit8ArrayDecode(message));
  console.log('MQ消息通讯：获取消息体>> ', data);
  console.log('packet:',packet)
  var type = data.type;
  if(topic==MQ_TOPIC){
  //判断操作type
    switch (type) {
      case 'RemindTheReviewerToCheckIn':
        if(data.info.phone == userwpinfo.username){
          Vue.prototype.$bus.$emit("RemindTheReviewerToCheckIn", data);
        }
		break;
      case 'ModelDisconnect':
        if (data.info.userid == userwpinfo.userid) {
          store.commit('SET_MODEL_ONLINE', false);
        }
        break;
      case 'ModelOnLine':

		if (data.info.userid == userwpinfo.userid) {
		Vue.prototype.$bus.$emit('showMenu')
		store.commit('SET_MODEL_ONLINE', true);
		}
		break;
      //type为Login的消息已不使用
      case 'Login':
        Vue.prototype.$bus.$emit("changeOnlinePersonList", data);
        Vue.prototype.$bus.$emit("changeOnlinePersonListCount", data);
        console.log('MQ消息通讯：Login>> 更新登录人员列表>>changeOnlinePersonList');
        break;
      case 'LoginOut':
        Vue.prototype.$bus.$emit("changeOnlinePersonListCount", data);
        Vue.prototype.$bus.$emit("changeOnlinePersonList", data);
        Vue.prototype.$bus.$emit("clearAudio");
        console.log('MQ消息通讯：LoginOut>>  更新登录人员列表>>changeOnlinePersonList');
        break;
      case 'SignIn':
        Vue.prototype.$bus.$emit("changeSignInList", data);
        console.log('MQ消息通讯：SignIn>>  更新签到人员列表>>changeSignInList');
        break;
      case 'ApplyForScreen':
        if (userwpinfo.userrole.includes('会议管理员') || userwpinfo.userrole.includes('值班长')) {
          Vue.prototype.$bus.$emit("ApplyForScreen", data);
          console.log('MQ消息通讯：ApplyForScreen>>  会议管理员接收投屏申请>>ApplyForScreen');
        }
        break;
      case 'AuditTraining':
        if (data.receiveid == userwpinfo.userid) {
          Vue.prototype.$bus.$emit("AuditTraining", data);
          console.log('MQ消息通讯：AuditTraining>>  申请人接收会议管理员培训申请审核结果>>AuditTraining');
        }
        break;
      case 'OpenTrainingFullScreen':
        Vue.prototype.$bus.$emit("OpenTrainingFullScreen", data);
        console.log('MQ消息通讯：OpenTrainingFullScreen>>  会议管理员培训申请审核通过通知全场拉流培训>>OpenTrainingFullScreen');
        break;
      case 'CloseTraining':
        Vue.prototype.$bus.$emit("CloseTraining", data);
        console.log('MQ消息通讯：CloseTraining>>  会议管理员培训申请审核通过通知全场拉流培训>>CloseTraining');
        break;
      case 'AuditScreen':
        if (data.receiveid == userwpinfo.userid) {
          Vue.prototype.$bus.$emit("AuditScreen", data);
          console.log('MQ消息通讯：ApplyForScreen>>  申请人接收会议管理员投屏申请审核结果>>AuditScreen');
        }
        break;
      case 'ApplyForTraining':
        if (userwpinfo.userrole.includes('会议管理员')) {
          Vue.prototype.$bus.$emit("ApplyForTraining", data);
          console.log('MQ消息通讯：ApplyForTraining>>  会议管理员接收培训投屏申请>>ApplyForTraining');
        }
        break;
      case 'CloseScreen':
        Vue.prototype.$bus.$emit("CloseScreen", data);
        console.log('MQ消息通讯：CloseScreen>>  投屏申请人结束投屏>>CloseScreen');
        break;
      case 'ApplyForAudio':
        if (userwpinfo.userrole.includes('会议管理员')) {
          Vue.prototype.$bus.$emit("ApplyForAudio", data);
          console.log('MQ消息通讯：ApplyForScreen>>  会议管理员接收发言申请>>ApplyForScreen');
        }
        break;
      case 'AuditAudio':
        if (data.receiveid == userwpinfo.userid) {
          Vue.prototype.$bus.$emit("AuditAudio", data);
          console.log('MQ消息通讯：ApplyForScreen>>  申请人接收会议管理员发言申请审核结果>>AuditScreen');
        }
        break;
      case 'MaxScreen':
        if (data.receiveid == userwpinfo.userid) {
          Vue.prototype.$bus.$emit("MaxScreen", data);
          console.log('MQ消息通讯：MaxScreen>>  申请人接收会议管理员发言申请审核结果>>MaxScreen');
        }
        break;
      case 'CloseAudio':
        Vue.prototype.$bus.$emit("CloseAudio", data);
        console.log('MQ消息通讯：CloseAudio>> 发言申请人结束发言>>CloseAudio');
        break;
      case 'ApplyForSpeech':
        //审核人
        if (userwpinfo.userrole.includes('会议管理员')) {
          Vue.prototype.$bus.$emit("ApplyForSpeech", data);
          console.log('MQ消息通讯：ApplyForSpeech>>  会议管理员接收演讲区发言申请>>ApplyForSpeech');
        }
        //申请人 等待提示
        if(data.info.userid==userwpinfo.userid){
          Vue.prototype.$this.$confirm({
            title: '演讲台发言',
            content: '等待管理审核通过',
            cancelButtonProps: {style: {display: 'none'}},
            onOk() {
            },
          });
        }
        break;
      case 'AuditSpeech':
        if (data.receiveid == userwpinfo.userid) {
          Vue.prototype.$bus.$emit("AuditSpeech", data);
          console.log('MQ消息通讯：AuditSpeech>>  申请人接收会议管理员演讲区发言申请审核结果>>AuditSpeech');
        }
        break;
      case 'CloseSpeech':
        Vue.prototype.$bus.$emit("CloseSpeech", data);
        console.log('MQ消息通讯：CloseSpeech>>  发言人离开演讲区>>CloseSpeech');
        break;
      case 'OneToOne':
        var userId = userwpinfo.userid
        console.log('bus:',Vue.prototype.$bus);
        console.log('bus.emit:',Vue.prototype.$bus.$emit);
		if (data.receiveid == userId) {
            Vue.prototype.$bus.$emit('message', data)
		}
        break;
      case 'OneToGroup':
        userId = userwpinfo.userid
        var ids = data.receiveid
		console.log('ids:',data.receiveid);
		console.log('userId:',userId);
        for (let i = 0; i < ids.length; i++) {
          console.log('receiveid:userId',ids[i],userId)

          if (ids[i] == userId) {
			console.log('执行事件');
			Vue.prototype.$bus.$emit('message', data)
          }

        }
        break;
      case 'OneToOneRead':
        userId = userwpinfo.userid
        // if (data.receiveid == userId) {
          Vue.prototype.$bus.$emit('chanMessageRead', data)
        // }
        break;
      case 'OnlinePersonKeepAlive':
        send({
          channelid: '12138',
          type: 'OnlinePersonKeepAlive',
          sendid: userId,
          receiveid: 'bg',
          time: new Date().toLocaleString().replace(/\//g, '-'),
          timestamp: new Date().getTime(),
        });
        break;
      case 'OpenAudio' :
        Vue.prototype.$bus.$emit("OpenAudio", data);
        break;
      case 'WalkToStage':
        if (data.receiveid == userwpinfo.userid) {
          Vue.prototype.$bus.$emit("WalkToStage", data);
        }
        break;
      case 'OpenSpeech':
        Vue.prototype.$bus.$emit("OpenSpeech", data);
        break;
      case 'NearByPerson':
        Vue.prototype.$bus.$emit("NearByPerson", data);
        break;
      case 'SendHeartBeat':
          send({
              channelid: '12138',
              type: 'AnswerHeartBeat',
              sendid: userId,
              receiveid: 'admin',
              time: new Date().toLocaleString().replace(/\//g, '-'),
              timestamp: new Date().getTime(),
          });
          break;
      case 'PersonNotFound':
          if (data.info.fromid == userwpinfo.userid) {
            Vue.prototype.$bus.$emit("PersonNotFound",data);
          }
          break;
      case 'ExecMuteForAll':
        //打开麦克风
        break;
      case 'UnMuteForAll':
        //禁用麦克风
        break;
      case 'ApplyUnMute':
        //申请解除麦克风
        //接受者是会议管理员
        if (userwpinfo.userrole.includes('会议管理员')) {
          //解除窗口
        }
        break;
      case 'AnswerApplyUnMute':
        //响应申请麦克风
        //是申请人吗
        if (data.receiveid == userwpinfo.userid) {
          //同意
          if(data.info.agree){
            //弹窗
            Vue.prototype.$this.$confirm({
              title: '主持人同意申请',
              content: '主持人已同意您的解除静音申请',
              okText: '解除静音',
              cancelText: '保持静音',
              onOk() {
                //解开麦克风
              },
              onCancel() {
              }
            });
          }else{
            //不同意
            //弹窗
            this.$message.warning(
              '主持人不允许解除静音',
              2,
            );
          }
        }
		break;
      case 'applyForPrivateMeeting':
        if (data.receiveid == userId) {
          Vue.prototype.$bus.$emit('applyForPrivateMeeting', data)
        }
        break;
      case 'AgreeToPrivateMeeting':
          Vue.prototype.$bus.$emit('AgreeToPrivateMeeting', data)
        break;
      case 'EndPrivateMeeting':
          Vue.prototype.$bus.$emit('EndPrivateMeeting', data)
        break;
      case 'ScriptStateChange':
          Vue.prototype.$bus.$emit('ScriptStateChange', data)
        break;
      case 'ScriptStateChangeJiedan':
          Vue.prototype.$bus.$emit('ScriptStateChangeJiedan', data)
        break;
      case 'HandoverApplication':
        if (data.receiveid == userwpinfo.userid) {
          Vue.prototype.$bus.$emit('HandoverApplication', data)
        }
          break;
      case 'HandoverApplicationResult':
        if (data.receiveid == userwpinfo.userid) {
          Vue.prototype.$bus.$emit('HandoverApplicationResult', data)
        }
          break;
      case 'getWorkOrderStatistics':
        Vue.prototype.$bus.$emit('getWorkOrderStatistics', data)
        break;
      case 'Danbian9':
        if (data.receiveid == userwpinfo.userid) {
          Vue.prototype.$bus.$emit('Danbian9', data)
        }
          break;
      case 'RefreshCount':
        Vue.prototype.$bus.$emit('RefreshCount')
        break;
      case 'ScreenClick':
        if (data.info.userID == userwpinfo.userid) {
          Vue.prototype.$bus.$emit("ScreenClick", data);
        }
        break;
      case 'ViewChanges':
        if (data.receiveid.includes(userwpinfo.username)) {
          Vue.prototype.$bus.$emit("ViewChanges", data);
        }
        break;
      case 'SitChairSuccess':
        if (data.info.userID.includes(userwpinfo.userid)) {
          Vue.prototype.$bus.$emit("SitChairSuccess", data);
        }
        break;
      default:

    }
  //公共主题
  }else if(topic==MQ_COMMON_TOPIC){
    //判断操作类型
    console.log('判断操作类型 :>> ', );
    switch (data.type) {
      //会议互斥（1个人不能同时存在多个会议室）
      case 'LoginMutex':
        //发现重复用户
      if (data.sendid == userwpinfo.userid) {
        //排除发送客户端
        var clientId=store.getters.clientId;
        if(clientId!=data.info.clientId){
          //退出登录
          Vue.ls.remove(ACCESS_TOKEN)
          Vue.prototype.$this.$router.replace({path:'/user/login'})
          //当同类型端挤占时，不清楚在线信息
          if(data.info.loginType!='meeting'){
            store.dispatch('Logout').then(async () => {
              send({
                channelid: '12138',
                type: 'LoginOut',
                sendid: store.getters.decryptUserwp.userid,
                receiveid: 'all',
                info: {
                  userid: store.getters.decryptUserwp.userid,
                },
                time: new Date().toLocaleString().replace(/\//g, '-'),
                timestamp: new Date().getTime(),
              });
              disconnect();
            })
          }else{
            disconnect();
          }
        }
      }
    }
  }



}

/**
 * 关闭
 */
async function disconnect() {
  var mqclient = await store.getters.mqClient;
  if (mqclient) {
    mqForMqtt.unsubscribe(mqclient, MQ_TOPIC)
    mqForMqtt.unsubscribe(mqclient, MQ_COMMON_TOPIC)
    mqForMqtt.disconnect(mqclient);
    store.commit('SET_MQCLIENT', null);
  } else {
    console.log('mqClient为空 :>> ', mqclient);
  }
}

/**
 * 关闭回调
 */
async function closeCallBack() {
  var mqclient = await store.getters.mqClient;
  //mqClient 为 null 为正常退出
  console.log('mqclientdisconnected :>> ', mqclient);
  if (mqclient) {
    if (!mqclient.connected) {
      console.log('重连时间 :>> ', new Date().toLocaleString());
      mqclient.reconnect();
    }
  } else {
    console.log(' 连接关闭:>> ', new Date().toLocaleString());
  }
}


export default {
  connect,
  send,
  disconnect,
  sendByTopic

}

